package com.pudu.mydemo.entity;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.Socket;
import java.util.ArrayList;

import com.pudu.mydemo.utils.ClientConnectUtils;
import com.pudu.mydemo.utils.ConstantUtils;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;

public class ClientThread implements Runnable {
	
	MulticastSocket multicastSocket;
	InetAddress serverAddress;
	ArrayList<String> ipdatas ;
	Bundle bundle;

	Socket socket;
	boolean flag = true;
	Context context;
	//初始化单例对象
	TcpStringEntity tcpStringEntity = TcpStringEntity.getInstance();
	

	//空构造函数
	public ClientThread(){
	}
	
	@Override
	public void run() {
		ipdatas = new ArrayList<>();

		try {
			multicastSocket = new MulticastSocket(ConstantUtils.MULTICAST_PORT);
			serverAddress = InetAddress.getByName(ConstantUtils.GROUP_IP);
			if (!serverAddress.isMulticastAddress()) {// 测试是否为多播地址

				throw new Exception("请使用多播地址");

			}
			// 将该MulticastSocket对象加入到指定的多点广播地址,
			// MulticastSocket使用public void joinGroup(InetAddress mcastaddr)
			// throws IOException方法加入指定组.

			multicastSocket.joinGroup(serverAddress);
			// 创建一个byte数组用于接收
			byte data[] = new byte[1024];
			
			while (flag) {
				// 创建一个空的DatagramPackage对象
				bundle = new Bundle();
				DatagramPacket dp = new DatagramPacket(data, data.length);
				multicastSocket.receive(dp);
				Message msg = new Message();
				
				if (dp.getAddress() != null) {
					  final String quest_ip = dp.getAddress().toString();
					  
					    //循环获得本地主机ip
		                String host_ip = ClientConnectUtils.getLocalHostIp();
		                //host_ip本机ip
		                Log.i("lgq","host_ip:  --------------------  " + host_ip);
		                Log.i("lgq","quest_ip: --------------------  " + quest_ip.substring(1));
		                
		                /* 若udp包的ip地址 是 本机的ip地址的话，丢掉这个包(不处理)*/
		                if( (!host_ip.equals(""))  && host_ip.equals(quest_ip.substring(1))) {
		                    continue;
		                }

		                boolean equal_flag = false;
		                for (int i = 0; i < ipdatas.size(); i++) {
							if (ipdatas.get(i).equals(quest_ip.substring(1))) {
								equal_flag = true;
								break;
							}
						}
					//不显示本机的ip
		                if (!equal_flag)
		                	ipdatas.add(quest_ip.substring(1));
					//发送显示数据到列表中

					//tcp一直都在发送数据
					socket = new Socket(quest_ip.substring(1),ConstantUtils.TCP_PORT);
					//第二个参数为True则为自动flush
					PrintWriter out = new PrintWriter(
							new BufferedWriter(new OutputStreamWriter(
									socket.getOutputStream())), true);
					//将接收到的数据，通过tcp socket 传到服务端，所以其他robot就可以接收到这个数据。
					if (tcpStringEntity.getStr().equals("")){
						return;
					}
					System.out.println("收到数据来自["+quest_ip.substring(1)+"]:"+tcpStringEntity.getStr());
					out.println(tcpStringEntity.getStr());
				}
				Thread.sleep(5000);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if (!flag) {
				if (multicastSocket != null)
					multicastSocket.close();
			}
		}
	}
}